package com.sinoglobal.sinostore.activity;

import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.StateBaseActivity;
import com.sinoglobal.sinostore.adapter.SearchTextAdapter;
import com.sinoglobal.sinostore.utils.SharedPreferenceUtil;
import com.sinoglobal.sinostore.utils.TextUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LK
 * @title: GoodsListActivity.java
 * @package com.chiliring.sinostore.activity
 * @description: TODO(商品列表Activity)
 * @date 2015-1-14 上午10:54:45
 */
public class SearchListActivity extends StateBaseActivity implements OnClickListener {

    private ListView listView;
    private EditText etSearch;
    private ImageButton titleBtnBack;
    private TextView btnClearSearch;


    List<String> searchHistoryList = new ArrayList<String>();
    SearchTextAdapter searchTextAdapter;

    private boolean isList = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_activity_search_list);
        openChenJInShi();
        initView();

        initData();
    }

    private void initData() {

    }

    private void initView() {
        listView = getViewById(R.id.lvSearch);
        etSearch = getViewById(R.id.et_search_goods);
        titleBtnBack = getViewById(R.id.title_btn_left);
        btnClearSearch = getViewById(R.id.btn_clear_search);


        titleBtnBack = (ImageButton) this.findViewById(R.id.title_btn_left);
        titleBtnBack.setVisibility(View.VISIBLE);
        titleBtnBack.setOnClickListener(this);
        btnClearSearch.setOnClickListener(this);
        String searchHistory = SharedPreferenceUtil.getString(this, "searchHistory");
        if (!TextUtil.stringIsNull(searchHistory)) {
            String[] searchArr = searchHistory.split(",");
            for (int i = 0; i < searchArr.length; i++) {
                searchHistoryList.add(searchArr[i]);
            }
        }
        searchTextAdapter = new SearchTextAdapter(this, searchHistoryList);
        if (null != searchHistoryList && searchHistoryList.size() > 0) {
            btnClearSearch.setVisibility(View.VISIBLE);
        } else {
            btnClearSearch.setVisibility(View.INVISIBLE);
        }
        listView.setAdapter(searchTextAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                etSearch.setText(searchTextAdapter.getItem(position));
                setCursor();
                bundle.putString("searchText", etSearch.getText().toString());
                toActivity(GoodsListActivity.class, bundle);
                searchHistoryList.remove(etSearch.getText().toString());
                searchHistoryList.add(0, etSearch.getText().toString());
                finish();
            }
        });
        etSearch.setText(getIntent().getStringExtra("searchText"));
        isList = getIntent().getBooleanExtra("isList", false);
        setCursor();
        etSearch.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                LogUtils.d("actionId==" + actionId);
                switch (actionId) {
                    case EditorInfo.IME_ACTION_SEARCH:
                        //搜索按钮
//			           if (TextUtil.stringIsNotNull(etSearch.getText().toString())) {
                        Bundle bundle = new Bundle();
                        bundle.putString("searchText", etSearch.getText().toString());
                        toActivity(GoodsListActivity.class, bundle);
                        searchHistoryList.remove(etSearch.getText().toString());
                        searchHistoryList.add(0, etSearch.getText().toString());
                        finish();
//					   }else{
//						   showShortToast("您还没有输入搜索内容哦");
//					   }
                        break;
                }
                return true;

            }
        });

    }

    private void setCursor() {
        CharSequence text = etSearch.getText();
        if (text instanceof Spannable) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, text.length());
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.title_btn_left) {
            this.finish();
        } else if (id == R.id.btn_clear_search) {
            SharedPreferenceUtil.removeString(this, "searchHistory");
            btnClearSearch.setVisibility(View.INVISIBLE);
            searchHistoryList.clear();
            searchTextAdapter.notifyDataSetChanged();
            etSearch.setText("");
        }
    }

    @Override
    public void finish() {
        String search = etSearch.getText().toString();
        if (TextUtils.isEmpty(search)) {
            if (isList) {
                Bundle bundle = new Bundle();
                bundle.putString("searchText", "");
                toActivity(GoodsListActivity.class, bundle);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                return;
            }
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        if (searchHistoryList.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0, lenth = Math.min(5, searchHistoryList.size()); i < lenth; i++) {
                sb.append(searchHistoryList.get(i))
                        .append(",");

            }
            sb.deleteCharAt(sb.lastIndexOf(","));
            SharedPreferenceUtil.saveString(this, "searchHistory", sb.toString());
        }
        super.onDestroy();
    }
}
